package javaTest05.exercise02.sever;

import javaTest05.utils.LogUtils;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class ChatServer {

    private ArrayList<ClientSocketHandler> clientSocketHandlerList;
    public ChatServer(){
        clientSocketHandlerList = new ArrayList<>();
    }
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(1314);
            LogUtils.info("系统提示:服务器已启动...");

            while (true){

                Socket socket = serverSocket.accept();//获取连接队列中的链接

                ClientSocketHandler clientSocketHandler = new ClientSocketHandler(socket, clientSocketHandlerList);//创建客户端处理对象

                String clientAddress = String.valueOf(socket.getRemoteSocketAddress());

                Thread serverThread = new Thread(clientSocketHandler,clientAddress);//开辟新线程

                clientSocketHandlerList.add(clientSocketHandler);//加入到连接池中

                LogUtils.info(String.format("与客户端:%s 建立连接,当前连接数为:%d",clientAddress, clientSocketHandlerList.size()));

                serverThread.start();//线程准备运行

            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
